package com.iterative.log.filter;

import java.net.InetAddress;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.MDC;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.sun.org.apache.bcel.internal.generic.IFGE;

public class LogFilter extends HandlerInterceptorAdapter{

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String reqIP = request.getRemoteAddr();
		InetAddress addr = InetAddress.getLocalHost();
		String localhostIP = addr.getHostAddress().toString();//获得本机IP
		String userId = null;
		if(SecurityUtils.getSubject().getPrincipal()==null){
			userId = "未登录";
		}else{
		 userId = SecurityUtils.getSubject().getPrincipal().toString();
		}
		String method = request.getMethod();
		String reqUrl = request.getRequestURL().toString();
		MDC.put("reqIP", reqIP);
		MDC.put("localhostIP", localhostIP);
		MDC.put("userId", userId);
		MDC.put("method", method);
		MDC.put("reqUrl", reqUrl);
		
		
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		MDC.remove("reqIP");
		MDC.remove("localhostIP");
		MDC.remove("userId");
		MDC.remove("method");
		MDC.remove("reqUrl");
		super.afterCompletion(request, response, handler, ex);
	}
	
	

}
